package com.middlegroup.subjectpay.service.impl;

import com.middlegroup.common.enums.ServiceType;
import com.middlegroup.common.exception.ErrorMsg;
import com.middlegroup.common.model.TransResult;
import com.middlegroup.subjectpay.dto.TransRequest;
import com.middlegroup.subjectpay.entity.CardBin;
import com.middlegroup.subjectpay.entity.SubjectInBills;
import com.middlegroup.subjectpay.entity.ThirdProtocolBindCard;
import com.middlegroup.subjectpay.service.*;
import com.middlegroup.subjectpay.service.empty.EmptyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by pc on 2019/1/14.
 */
@Service
@Slf4j
public class DeductServiceImpl implements DeductService {
    @Resource
    private CardBinService cardBinService;
    @Resource
    private SubjectInBillsService subjectInBillsService;
    @Resource
    private ChangpayService changpayService;
    @Resource
    private HelipayService helipayService;
    @Resource
    private KjtpayService kjtpayService;
    @Resource
    private EmptyService emptyService;

    @Resource
    private ThirdProtocolBindCardService thirdProtocolBindCardService;

    @Override
    public TransResult deduct(TransRequest request) {
        if (StringUtils.isBlank(request.getServiceType())){
            request.setServiceType(ServiceType.DEDUCT.name());
        }

        TransResult transResult = new TransResult();
        transResult.setBillNo(request.getBillNo());
        transResult.setMerchantBillNo(request.getMerchantBillNo());
        transResult.setAmount(request.getAmount());
        transResult.setTransStatus(0);
        transResult.setTransTime(System.currentTimeMillis());

        SubjectInBills subjectInBills=new SubjectInBills();
        subjectInBills.setSubjectCode(request.getSubjectCode());
        subjectInBills.setMerchantBillNo(request.getMerchantBillNo());
        subjectInBills.setBillNo(request.getBillNo());
        subjectInBills.setChannelCode(request.getChannelCode().getCode());
        subjectInBills.setServiceType(request.getServiceType());
        subjectInBills.setAmount(request.getAmount());
        subjectInBills.setStatus(0);

        boolean rt = false;
        try {
            rt = subjectInBillsService.insert(subjectInBills);
        }catch (Exception e){
            log.error("插入主体端入款订单表(t_subject_in_bills)失败:"+request.getBillNo(),e);
        }

        if (!rt) {
            //插入失败
            transResult.setTransStatus(2);
            transResult.setMsg("插入主体端出款订单表(t_subject_in_bills)失败:"+request.getBillNo());
            return transResult;
        }

        //校验参数
        if (StringUtils.isBlank(request.getMerchantBillNo())){
            subjectInBills.setStatus(2);
            subjectInBillsService.updateById(subjectInBills);

            transResult.setTransStatus(2);
            transResult.setMsg(ErrorMsg.EMPTY_MERCHANTBILLNO);
            return transResult;
        }
        if (StringUtils.isBlank(request.getBillNo())){
            subjectInBills.setStatus(2);
            subjectInBillsService.updateById(subjectInBills);

            transResult.setTransStatus(2);
            transResult.setMsg(ErrorMsg.EMPTY_BILLNO);
            return transResult;
        }
        if (null == request.getChannelCode()){
            subjectInBills.setStatus(2);
            subjectInBillsService.updateById(subjectInBills);

            transResult.setTransStatus(2);
            transResult.setMsg(ErrorMsg.EMPTY_CHANNELCODE);
            return transResult;
        }
        if (StringUtils.isBlank(request.getSubjectCode())){
            subjectInBills.setStatus(2);
            subjectInBillsService.updateById(subjectInBills);

            transResult.setTransStatus(2);
            transResult.setMsg(ErrorMsg.EMPTY_SUBJECTCODE);
            return transResult;
        }

        //获得bankCode
        CardBin cardBin = cardBinService.getBankInfoByCardNo(request.getCardNo());
        if (null == cardBin){
            subjectInBills.setStatus(2);
            subjectInBillsService.updateById(subjectInBills);

            transResult.setTransStatus(2);
            transResult.setMsg(ErrorMsg.UNKNOWN_CARD_NO);
            return transResult;
        }

        request.setCardBin(cardBin.getBankCode());

        /**
         * 此处一定要注意，调用第三方渠道接口必须返回TransResult，不可为空，且保证异常在接口中已处理
         */
        switch (request.getChannelCode()){
            case CH1111111:
                try{
                    //TODO 调用第三方通道接口：畅捷
                    transResult=changpayService.deduct(request);
                }catch (Exception e){
                    log.error("CH1111111第三方通道畅捷交易接口调用失败"+request.getBillNo(),e);
                }
                break;
            case CH1111112:
                try{
                    //TODO 调用第三方通道接口：畅捷
                    transResult=changpayService.deduct(request);
                }catch (Exception e){
                    log.error("CH1111112第三方通道畅捷交易接口调用失败"+request.getBillNo(),e);
                }
                break;
            case EMPTY0000002:
                //TODO 模拟渠道
                transResult = emptyService.deduct(request);
                break;
            case CH0000006:
                // 合利宝代扣
                if (StringUtils.isBlank(request.getProtocolNo())) {
                    //查询当前渠道的协议号
                    ThirdProtocolBindCard thirdProtocolBindCardFind = new ThirdProtocolBindCard();
                    thirdProtocolBindCardFind.setSubjectCode(request.getSubjectCode());
                    thirdProtocolBindCardFind.setChannelCode(request.getChannelCode().getCode());
                    thirdProtocolBindCardFind.setCardNo(request.getCardNo());
                    thirdProtocolBindCardFind.setIdCard(request.getIdCard());
                    thirdProtocolBindCardFind.setStatus(1);
                    ThirdProtocolBindCard thirdProtocolBindCard = thirdProtocolBindCardService.getLastOne(thirdProtocolBindCardFind);
                    if (null != thirdProtocolBindCard && StringUtils.isNotBlank(thirdProtocolBindCard.getProtocolNo())) {
                        request.setProtocolNo(thirdProtocolBindCard.getProtocolNo());
                    }
                }
                if (StringUtils.isBlank(request.getProtocolNo())) {
                    // 首次支付
                    transResult = helipayService.deduct(request);
                } else {
                    // 二次支付
                    transResult = helipayService.secondDeduct(request);
                }
            default:
                transResult.setTransStatus(2);
                transResult.setMsg("未找到相应channelCode!");
        }

        //是否更新bills表状态
        boolean ifUpdateBillStatus = null != transResult && null != transResult.getTransStatus() && (transResult.getTransStatus().intValue()==1 || transResult.getTransStatus().intValue()==2);
        if (ifUpdateBillStatus){
            subjectInBills.setStatus(transResult.getTransStatus());
            subjectInBillsService.updateById(subjectInBills);
        }

        return transResult;
    }
}
